<template>
	<view class="box">
		<view class="box-image">
			<image v-if="userData" :src="userData.recodeCodeImgUrl" mode=""></image>
		</view>
		<view class="box-btn">
			<button  class="btn" data-name="shareBtn" open-type="share">
				<image src="http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_16919959242594088.png" mode=""></image>
				<text>分享到微信</text>
			</button>
			
			<!-- <button  class="btn" data-name="shareBtn" open-type="share">
				<image src="http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_16919959360183784.png" mode=""></image>
				<text>分享到朋友圈</text>
			</button> -->
			<view class="box-btn-item" @click="handleshowfenxiang()">
				<image src="http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_169199594642264.png" mode=""></image>
				<text>图片下载</text>
			</view>
			<view class="box-btn-item" @click="saveShareImg(1)">
				<image src="http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_169199594642264.png" mode=""></image>
				<text>推荐码下载</text>
			</view>
		</view>
		<u-mask :show="showfenxiang">
			<view class="warp1">
				<view class="" v-if="isCanvas">
					<canvas :style="{ width:  '280px', height: '540px' }" canvas-id="myCanvas" id="myCanvas"></canvas>
				</view>
				<view class="xiazai" v-if="isflag">
					<image src="../../static/fx_gb.png" mode="" @click="handleclose"></image>
					<image src="../../static/fx_bd@2x.png" mode="" @click="saveShareImg(0)"></image>
				</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	var uploadImage = require('../../common/uploadFile.js');//地址换成你自己存放文件的位置
	var util = require('../../common/formatTime.js');
	export default {
		data() {
			return {
				share: {},
				userData:'',
				canvasW:280,
				canvasH:540,
				logoBg:'',
				ewmImg:'',
				imgUrl:'',
				isCanvas:true,
				type:'',
				showfenxiang:false,
				isflag:false
			}
		},
		onLoad() {
			this.getUserInfo()
		},
		methods: {
			//用户信息
			async getUserInfo(){
				const res = await this.$u.api.getUserInfo()
				this.userData = res.data
				const params = 'recodeCode=' + res.data.recodeCode
				this.share = { // 分享到微信和朋友圈
					title: '嗨美汇',
					path: '/pages/index/index?' + params,
					imageUrl: 'http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_16919795818803423.png',
					desc:'嗨美汇',
					content:'嗨美汇是一个为百业赋能的数字化营销平台'
				}
			},
			// 获取图片信息
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			
			// 获取设备信息
			getSystemInfo(){
				return new Promise((req, rej) => {
					uni.getSystemInfo({
					    success: function (res) {
					        req(res)
					    }
					});
				})
			},
			//打开分享
			handleshowfenxiang(){
				this.showfenxiang = true
				this.isCanvas = true
				this.createCanvasImage()
				
			},
			//关闭
			handleclose(){
				this.showfenxiang = false
				this.isCanvas = false
				this.isflag = false
			},
			async createCanvasImage(){
				var that = this
				// 获取设备信息，主要获取宽度，赋值给canvasW 也就是宽度：100%
				this.SystemInfo = await this.getSystemInfo();
				// 获取商品主图，二维码信息，APP端会返回图片的本地路径（H5端只能返回原路径）
				const logo = 'https://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_16919795818803423.png'
				this.logoBg = await this.getImageInfo(logo);
				this.ewmImg = await this.getImageInfo(this.userData.recodeCodeImgUrl);
				this.canvasW = 280; // 画布宽度
				this.canvasH = 540;  // 画布高度 = 主图高度+二维码高度 + 文字图片的间距（大概50）
				
				// 如果主图，二维码图片，设备信息都获取成功，开始绘制海报，这里需要用setTimeout延时绘制，否则可能会出现图片不显示。
				if(this.logoBg.errMsg == 'getImageInfo:ok' && this.ewmImg.errMsg == 'getImageInfo:ok' ){
					uni.showToast({
						icon:'loading',
						mask:true,
						duration:10000,
						title: '海报绘制中',
					});
					setTimeout(()=>{
						this.isflag = true
						var ctx = uni.createCanvasContext('myCanvas', this);
						// 填充背景色，白色
						ctx.setFillStyle('#ffffff'); // 默认白色
						ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度，高度)
						//绘制logo
						//ctx.drawImage(this.logo.path, 83, 24, 146, 47) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
						
						// 绘制背景
						ctx.drawImage(this.logoBg.path, 0, 0, 280, 540)
						//绘制二维码
						ctx.drawImage(this.ewmImg.path, 90,240,100,100) // 推进去图片
						
						ctx.draw(true,(ret)=>{ // draw方法 把以上内容画到 canvas 中。
							console.log(ret) 
							uni.showToast({
								icon:'success',
								mask:true,
								title: '绘制完成',
							});
							uni.canvasToTempFilePath({ // 保存canvas为图片
								canvasId: 'myCanvas',
								quality: 1,
								
								complete: function(res) {
									// 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
									console.log(res,11111)
									that.updateImage(res)
									//that.imgUrl = res.tempFilePath
								} ,
							})
						});
					},1500)
				}else{
					console.log('err')
				}
			},
			updateImage(res){
				var that = this
				var nowTime = util.formatTime(new Date());
				uploadImage(res.tempFilePath, 'hmh/',
				  function (result) {
				    console.log("======上传成功图片地址为：", result);
					that.imgUrl = result
				    //做你具体的业务逻辑操作
				 }, function (result) {
				  console.log("======上传失败======", result);
				  //做你具体的业务逻辑操作
				         uni.hideLoading()
				      }
				   )
			},
			// 保存到系统相册
			saveShareImg(data) {
				var that = this
				that.type = data
				uni.authorize({
				    /* 这个就是保存相册的 */
				    scope: 'scope.writePhotosAlbum',
				    success() {
				        /* 保存图片方法 */
				        that.img();
						
				    },
				    complete(res) {
				        console.log(res);
				        /* 这里判断一下如果没有授权重新打开设置选项 */
				        uni.getSetting({
				            success(res) {
				                if (!res.authSetting['scope.writePhotosAlbum']) {
				                    /* 打开设置的方法 */
				                    that.opensit();
				                }
				            }
				        });
				    }
				})
				
			},
			opensit() {
			    uni.showModal({
			        content: '由于您还没有允许保存图片到您相册里,这无法进行分享操作点击确定去允许授权',
			        success: function(res) {
			            if (res.confirm) {
			                /* 这个就是打开设置的API*/
			                uni.openSetting({
			                    success(res) {
			                        console.log(res.authSetting);
			                    }
			                });
			            } else if (res.cancel) {
			                uni.showModal({
			                    cancelText: '依然取消',
			                    confirmText: '重新授权',
			                    content: '很遗憾你点击了取消，这将无法进行分享操作，请慎重考虑',
			                    success: function(res) {
			                        if (res.confirm) {
			                            uni.openSetting({
			                                success(res) {
			                                    console.log(res.authSetting);
			                                }
			                            });
			                        } else if (res.cancel) {
			                            console.log('用户不授权');
			                        }
			                    }
			                });
			            }
			        }
			    });
			},
			img() {
				var that = this
			    /* 获取图片信息 */
			    uni.getImageInfo({
			        src: this.type===0?this.imgUrl:this.userData.recodeCodeImgUrl,
			        success: function(image) {
			            /* 保存图片到相册 */
			            uni.saveImageToPhotosAlbum({
			                filePath: image.path,
			                success: function() {
			                    console.log('save success');
								uni.showModal({
									title: '保存成功',
									content: '图片已成功保存到相册',
								});
								that.showfenxiang = false
								that.isCanvas = false
			                },
			                complete(res) {
			                    console.log(res);
			                }
			            });
			        }
			    });
			},
		},
	}
</script>

<style scoped lang="scss"> 
    .box-image{
		width: 750rpx;
		height: 1360rpx;
		background: url('http://hmh-app.oss-cn-beijing.aliyuncs.com/webStorage/web_16919795818803423.png') no-repeat;
		background-size: 100% 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 66rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #FFFFFF;
		line-height: 168rpx;
		text-shadow: 1px 1px 5px rgba(40,42,48,0.1);
		position: relative;
		z-index: 10;
	}
	.box-image image{
		width: 200rpx;
		height: 200rpx;
	}
	.box-btn{
		padding: 50rpx 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}
	.box-btn-item{
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.box-btn-item image{
		width: 88rpx;
		height: 88rpx;
	}
	.box-btn-item text{
		padding-top: 28rpx;
		font-size: 30rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #1F1F1F;
		line-height: 40rpx;
	}
	.btn{
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0;
		margin: 0;
		border: none;
		background: none;
	}
	.btn::after{
		border: none;
		padding: 0;
	}
	.btn image{
		width: 88rpx;
		height: 88rpx;
	}
	.btn text{
		padding-top: 28rpx;
		font-size: 30rpx;
		font-family: Adobe Heiti Std;
		font-weight: normal;
		color: #1F1F1F;
		line-height: 40rpx;
	}
	.canvas{
		position: absolute;
		left: 0;
		top: 0;
		z-index: 1;
	}
	
	.warp1 {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.xiazai{
		margin-top: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 0rpx 180rpx;
		width: 100%;
	}
	.xiazai image{
		width: 104rpx;
		height: 104rpx;
	}
</style>
